package com.czmh.etc.onlinepubsys.utils.httpclient;

import com.alibaba.fastjson.JSONObject;
import lombok.Cleanup;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @描述：httpclient工具类
 * @作者： Seven.
 * @创建日期：2017年2月15日 下午2:29:55.
 * @版本：1.0
 */
@Deprecated
public class HttpUtil {
    /**
     * //TODO get请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param params  请求参数
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static Result httpGet(String url, Map<String, String> headers, Map<String, String> params) throws ClientProtocolException, IOException {
        BasicCookieStore cookieStore = new BasicCookieStore();
        @Cleanup
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        url = (null == params ? url : url + "?" + parseParam(params));
        HttpGet get = new HttpGet(url);
        get.setHeaders(parseHeader(headers));
        CloseableHttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        Result result = new Result();
        result.setHttpClient(client);
        result.setCookies(cookieStore.getCookies());
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    /**
     * //TODO post请求
     *
     * @param url      请求地址
     * @param headers  请求头
     * @param params   请求参数
     * @param encoding 请求编码
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static Result httpPost(String url, Map<String, String> headers, Map<String, String> params, String encoding) throws ClientProtocolException, IOException {
        BasicCookieStore cookieStore = new BasicCookieStore();
        @Cleanup
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(JSONObject.toJSONString(params), Charset.forName("UTF-8"));
        s.setContentEncoding(encoding);
        post.setEntity(s);
        post.setHeaders(parseHeader(headers));
        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        Result result = new Result();
        result.setHttpClient(client);
        result.setCookies(cookieStore.getCookies());
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    /**
     * //TODO post请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static Result httpPost(String url, Map<String, String> params) throws ClientProtocolException, IOException {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        BasicCookieStore cookieStore = new BasicCookieStore();
        @Cleanup
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(JSONObject.toJSONString(params), Charset.forName("UTF-8"));
        s.setContentEncoding("UTF-8");
        post.setEntity(s);
        post.setHeaders(parseHeader(headers));
        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        Result result = new Result();
        result.setHttpClient(client);
        result.setCookies(cookieStore.getCookies());
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    /**
     * //TODO post请求
     *
     * @param url      请求地址
     * @param paramStr 请求参数
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static Result httpPost(String url, String paramStr) throws IOException {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        BasicCookieStore cookieStore = new BasicCookieStore();
        @Cleanup
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(paramStr, Charset.forName("UTF-8"));
        s.setContentEncoding("UTF-8");
        post.setEntity(s);
        post.setHeaders(parseHeader(headers));
        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        Result result = new Result();
        result.setHttpClient(client);
        result.setCookies(cookieStore.getCookies());
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    /**
     * //TODO post请求
     *
     * @param url      请求地址
     * @param headers  请求头
     * @param paramStr 请求参数
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static Result httpPost(String url, Map<String, String> headers, String paramStr)
            throws Exception {
        BasicCookieStore cookieStore = new BasicCookieStore();
        @Cleanup
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(paramStr, ContentType.APPLICATION_JSON);
        post.setEntity(s);
        post.setHeaders(parseHeader(headers));
        CloseableHttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        Result result = new Result();
        result.setHttpClient(client);
        result.setCookies(cookieStore.getCookies());
        result.setStatusCode(response.getStatusLine().getStatusCode());
        result.setHeaders(response.getAllHeaders());
        result.setHttpEntity(entity);
        result.setBody(EntityUtils.toString(entity));
        return result;
    }

    /**
     * //TODO 转换header
     *
     * @param headers
     * @return
     */
    private static Header[] parseHeader(Map<String, String> headers) {
        if (null == headers || headers.isEmpty()) {
            return getDefaultHeaders();
        }
        Header[] allHeader = new BasicHeader[headers.size()];
        int i = 0;
        for (String str : headers.keySet()) {
            allHeader[i] = new BasicHeader(str, headers.get(str));
            i++;
        }
        return allHeader;
    }

    /**
     * //TODO 默认header
     *
     * @return
     */
    private static Header[] getDefaultHeaders() {
        Header[] allHeader = new BasicHeader[2];
        allHeader[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
        allHeader[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
        return allHeader;
    }

    /**
     * //TODO 转换参数列表
     *
     * @param params
     * @return
     */
    private static String parseParam(Map<String, String> params) {
        if (null == params || params.isEmpty()) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (String key : params.keySet()) {
            sb.append(key + "=" + params.get(key) + "&");
        }
        return sb.substring(0, sb.length() - 1);
    }

    /**
     * 释放httpclient对象
     */
    public static void closeClient(CloseableHttpClient client) {
        if (null != client) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}